package cn.zhaozhiqi.controller;

import cn.zhaozhiqi.domain.Student;
import cn.zhaozhiqi.service.IStudentService;
import cn.zhaozhiqi.util.ExcelUtil;
import cn.zhaozhiqi.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 校园系统——学生控制管理层
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private IStudentService istudentService;

    /**
     * 查询全部教师资料
     * @return返回教师资料的集合
     */
    @GetMapping("/all")
    public R queryAll(){
        List<Student> list = istudentService.getAll();
        return R.ok(list);
    }
    //新增
    @Transactional
    @PostMapping("/insert")
    public R insert(@RequestBody Student student){
        try {
            istudentService.insert(student);
            return R.ok("新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("新增失败");
        }

    }

    //修改
    @Transactional
    @PostMapping("/update")
    public R update(@RequestBody Student student){

        try {
            istudentService.update(student);
            return R.ok("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("修改失败");
        }

    }

    //根据id删除
    @Transactional
    @DeleteMapping ("/delete/{id}")
    public R deleteById(@PathVariable("id")Long id){
        try {
            istudentService.deleteById(id);
            return R.ok("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("删除失败");
        }

    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        //1.查询出所有老师的信息
        List<Student> list = istudentService.getAll();
        //2.使用easypoi工具类实现导出
        ExcelUtil.exportExcel(list, "智慧校园管理系统-学生信息", "1",
                Student.class, "students", response);
    }

    @PostMapping("/import")
    public R importstudent(@RequestParam("file") MultipartFile file) throws
            IOException {
        List<Student> students = ExcelUtil.importExcel(file, Student.class);
        istudentService.addAllstudent(students);
        return R.ok("上传成功！");
    }

}
